using System;
using System.Web;
using Jaws.Core.Web;
using Jaws.Core.Web.Entities;
using Jaws.Core.Web.Entities.Pages;

namespace Jaws.Core.Web.Providers
{
    /// <summary>
    /// A site map provider for the Pages in BlogEngine.
    /// </summary>
    public class PageSiteMap : SiteMapProvider
    {
        PageCollection Pages = XmlCollectionBase<PageCollection, Page>.Load();

        public override SiteMapNode FindSiteMapNode(string rawUrl)
        {
            int i = rawUrl.IndexOf('?');
            string url = rawUrl;
            if (i > 0) url = rawUrl.Substring(0, i);
            int start = url.LastIndexOf('/') + 1;
            int stop = url.LastIndexOf('.');
            url = url.Substring(start, stop - start);

            foreach (Page page in Pages)
            {
                if ((page.ShowInList)
                    && url.Equals(Utils.RemoveIllegalCharacters(page.Title), StringComparison.OrdinalIgnoreCase))
                {
                    return new SiteMapNode(this, page.Id.ToString(), page.RelativeLink.ToString(), page.Title, page.Description);
                }
            }

            return null;
        }

        public override SiteMapNodeCollection GetChildNodes(SiteMapNode node)
        {
            var col = new SiteMapNodeCollection();
            var id = new Guid(node.Key);
            foreach (Page page in Pages)
            {
                if ((page.ShowInList) && page.Parent == id && page.ShowInList)
                    col.Add(new SiteMapNode(this, page.Id.ToString(), page.RelativeLink.ToString(), page.Title, page.Description));
            }

            return col;
        }

        public override SiteMapNode GetParentNode(SiteMapNode node)
        {
            var id = new Guid(node.Key);
            Guid parentId = Pages[id].Parent;
            if (parentId != Guid.Empty && parentId != id)
            {
                Page parent = Pages[parentId];
                if (parent.ShowInList)
                {
                    return new SiteMapNode(this, parent.Id.ToString(), parent.RelativeLink.ToString(), parent.Title, parent.Description);
                }
            }

            return null;
        }

        protected override SiteMapNode GetRootNodeCore()
        {
            Page page = Pages.GetHomePage();
            if (page != null)
                return new SiteMapNode(this, page.Id.ToString(), page.RelativeLink.ToString(), page.Title);

            return new SiteMapNode(this, Guid.Empty.ToString(), "~/", "Home");
        }
    }
}